package com.njupt.sellsec.ascpect;

import com.njupt.sellsec.domain.SellUser;
import com.njupt.sellsec.exception.SellerAuthorizeException;
import com.njupt.sellsec.redis.RedisService;
import com.njupt.sellsec.redis.SellUserKey;
import com.njupt.sellsec.service.Impl.SellUserServiceImpl;
import com.njupt.sellsec.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 21:47 2018/8/2
 * @Modified By:
 **/
@Aspect
@Component
@Slf4j
public class SellAuthorizeAspect {


    @Autowired
    private RedisService redisService;

    @Pointcut("execution(public * com.njupt.sellsec.controller.Se*.*(..))")
    public void verify(){

    }


    @Before("verify()")
    public void doVerify(){
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request =attributes.getRequest();
            Cookie cookie = CookieUtil.getCookie(request, SellUserServiceImpl.COOKIE_NAME_TOKEN);
            //查询Cookie
            if (cookie==null){
                log.warn("【登陆校验】Cookie中查不到token");
                throw new SellerAuthorizeException();
            }

            //查询redis
           String token = cookie.getValue();
            SellUser user = redisService.get(SellUserKey.token,token,SellUser.class);
            if(user==null){
                log.warn("【登陆校验】Cookie中查不到token");
                throw new SellerAuthorizeException();

            }

        }
}
